package ext.tianma.changeManager.config;

import java.rmi.RemoteException;
import java.util.Hashtable;
import java.util.Locale;
import java.util.Vector;

import ext.tianma.part.PartRelatedDocUtil;
import org.slf4j.LoggerFactory;

import wt.doc.WTDocument;
import wt.enterprise.EnterpriseHelper;
import wt.fc.PersistenceHelper;
import wt.fc.PersistenceServerHelper;
import wt.fc.QueryResult;
import wt.fc.collections.WTHashSet;
import wt.folder.Folder;
import wt.folder.FolderHelper;
import wt.inf.container.WTContainer;
import wt.inf.container.WTContainerRef;
import wt.part.WTPart;
import wt.part.WTPartDescribeLink;
import wt.part.WTPartHelper;
import wt.part.WTPartReferenceLink;
import wt.part.WTPartUsageLink;
import wt.session.SessionHelper;
import wt.util.WTException;
import wt.util.WTMessage;
import wt.util.WTProperties;
import wt.util.WTPropertyVetoException;
import wt.vc.VersionControlHelper;
import wt.vc.views.View;
import wt.vc.views.ViewHelper;
import wt.vc.views.ViewReference;
import wt.vc.wip.WorkInProgressHelper;
import ext.com.core.CoreUtil;
import ext.com.iba.IBAUtil;
import ext.generic.part.CusIBAUtil;
import ext.tianma.bom.workflow.SingletonBOM;
import ext.tianma.part.PartCommands;
import ext.tianma.part.forms.PartUtil;
import ext.tianma.part.forms.VersionPromoteProcessor;
import wt.workflow.engine.WfEngineHelper;

public class ChangeConfig {
	
	private static final org.slf4j.Logger logger = LoggerFactory.getLogger(ChangeConfig.class);
	
	private static String materialExcelPath = "" ;
	public static WTProperties wtProperties = null ;
	//原材料类型
	public static final String RAWMATERIAL = SingletonBOM.getInstance().getRawMaterial();
    static {
        try {
            wtProperties = WTProperties.getLocalProperties();
            materialExcelPath = wtProperties.getProperty("ext.tianma.part.materials");
        }
        catch (Throwable throwable) {
            throwable.printStackTrace(System.err);
            throw new ExceptionInInitializerError(throwable);
        }
    }
    
    /**
     * 创建物料的进阶版本
     * @param currentPart
     * @return
     * @throws WTException
     * @throws WTPropertyVetoException
     * @author xucr
     * @CreateDate 2021年1月20日
     */
    public static WTPart createNewPart(WTPart currentPart) throws WTException, WTPropertyVetoException {
    	/**
    	 * 逻辑来源于物料料号进阶流程
    	 * VersionPromoteProcessor.java
    	 * */
		if( currentPart != null ){
			if( WorkInProgressHelper.isCheckedOut(currentPart) ){
				throw new WTException( "零部件被检出，不能进行版本进阶。" );
			}
		}
		String number = currentPart.getNumber();
		logger.info("Debug  版本进阶   当前进阶的物料编号："+currentPart.getNumber());
		String softType = IBAUtil.getSoftType(currentPart).getLogicalIdentifier();
		softType = softType.substring(softType.indexOf(".")+1);
		Locale locale = SessionHelper.getLocale();
		if(softType.equals("C4")&&number.endsWith("K")) {
			String message=WTMessage.getLocalizedMessage("ext.tianma.resource.ResourceRB","PROMOTE_ERR",null,locale);
			throw new WTException(message);
		}
		WTPart newPart  = saveNewPart(currentPart);
		logger.info("Debug  版本进阶  另存为的物料编号："+newPart.getNumber());

		//创建部件后,终止由生命周期自动启动的流程
		WfEngineHelper.service.terminateObjectsRunningWorkflows(newPart);
		/**
		 * 进阶时不再使用A20视图，C06视图
		 */
		try {
			Vector partNumberEffectiveSite = IBAUtil.getIBAValue2(newPart, "partNumberEffectiveSite");
			if(partNumberEffectiveSite != null){
				partNumberEffectiveSite.remove("A20");
				partNumberEffectiveSite.remove("C06");
				String updatePartNumberEffectiveSite = "";
				for (int i = 0; i < partNumberEffectiveSite.size(); i++) {
					Object obj = partNumberEffectiveSite.get(i);
					if( obj instanceof String ){
						logger.info("Debug  版本进阶料号生效地" +  obj.toString());
						if("".equals(updatePartNumberEffectiveSite)){
							updatePartNumberEffectiveSite = (String) obj;
						} else{
							updatePartNumberEffectiveSite = updatePartNumberEffectiveSite + "," + (String) obj;
						}
						logger.info("Debug  版本进阶料号生效地总汇" +  updatePartNumberEffectiveSite);
					}
				}
				CusIBAUtil.forceSetEnumIBAValue( newPart , "partNumberEffectiveSite" , updatePartNumberEffectiveSite );
			}
		} catch (RemoteException e1) {
			e1.printStackTrace();
		}
		
		//删除使用关系
		Vector usagelinks2 =  CoreUtil.getPartUsageLinks(newPart);   
		WTHashSet set = new WTHashSet();
        for(int c = 0; c < usagelinks2.size(); c++) {
            WTPartUsageLink usagelink = (WTPartUsageLink)usagelinks2.elementAt(c);
            set.add(usagelink);
        }

        //删除描述关系
        QueryResult desclinks = WTPartHelper.service.getDescribedByDocuments(newPart);
        while(null!=desclinks&&desclinks.hasMoreElements()) {
        	WTDocument doc = (WTDocument) desclinks.nextElement();
        	logger.info("Debug 版本进阶   描述文档 的名称： "+doc.getName());
        	WTPartDescribeLink link = VersionPromoteProcessor.getDescribeLinkBetweenPartAndDoc(newPart, doc);
        	set.add(link);
        }
        
        //删除参考关系
        QueryResult reflinks = CoreUtil.getAssociatedReferenceDocuments(newPart);
        while(null!=reflinks&&reflinks.hasMoreElements()) {
        	WTDocument doc = (WTDocument) reflinks.nextElement();
        	logger.info("Debug 版本进阶   参考文档 的名称： "+doc.getName());
        	WTPartReferenceLink link = VersionPromoteProcessor.getReferenceLinkBetweenPartAndDoc(newPart, doc);
        	set.add(link);
        }
        //执行删除
        if(set.size() > 0) {
        	PersistenceServerHelper.manager.remove(set); 
        }
		//更新零部件默认单位
        try {
			String value=(String) IBAUtil.getIBAValue( newPart , "partEName");
			String unit=PartUtil.getRawMaterialsUnit(VersionPromoteProcessor.getWorkbook( materialExcelPath ).getSheetAt(1), value);
			VersionPromoteProcessor.changePartUnit( newPart , unit);
			 String whetherPartRecognize=(String) IBAUtil.getIBAValue( newPart , "whetherPartRecognize");
			 logger.info("whetherPartRecognize====>>"+whetherPartRecognize);
			 if("是".equals(whetherPartRecognize)) {
				 Hashtable<String, String> values = new Hashtable<String, String>();
				 values.put("whetherPartRecognize","否");
				 logger.info("values===>>"+values);
				 IBAUtil.setSoftTypeIBAValues(newPart, values);
				 newPart=(WTPart)PersistenceHelper.manager.save(newPart);
				 newPart=(WTPart)PersistenceHelper.manager.refresh(newPart);
				 logger.info("==样品承认设置成功=="+values);
			 }
		} catch (RemoteException e) {
			e.printStackTrace();
		}
        return newPart;
	}

	/**
	 * 根据旧物料另存为一个新物料
	 * 从ext\tianma\part\PartCommands.java,复制而来,由于逻辑不一致
	 * 本次修改,物料创建后,默认创建人为历史部件的创建人
	 * @param oldPart 就物料
	 * @return 新物料
	 * @throws WTException
	 * @throws WTPropertyVetoException
	 */
	public static WTPart saveNewPart(WTPart oldPart) throws WTException, WTPropertyVetoException {
		String newPartName = oldPart.getName();
		String newPartView = "Design";

		// String foldPath = oldPart.getFolderPath();//最后一对象结尾
		// if (!"/Default".equals(foldPath)) {
		// int lastIndex = foldPath.lastIndexOf("/");
		// foldPath = foldPath.substring(0, lastIndex);
		// }
		// 修改原因:此方法难道对象所在的文件夹路径不包含对象
		String foldPath = oldPart.getLocation();

		WTContainer container = oldPart.getContainer();
		Folder folder = FolderHelper.service.getFolder(foldPath, WTContainerRef.newWTContainerRef(container));
		WTPart newPart = (WTPart) EnterpriseHelper.service.newCopy(oldPart);
		newPart.setName(newPartName);
		View view = ViewHelper.service.getView(newPartView);
		ViewReference viewRef = ViewReference.newViewReference(view);
		newPart.setView(viewRef);
		newPart.setContainer(container);
		if (folder != null) {
			FolderHelper.assignLocation(newPart, folder);
		}
		//重新设置部件的创建者
		VersionControlHelper.assignIterationCreator(newPart,oldPart.getCreator());

		newPart = (WTPart) EnterpriseHelper.service.saveCopy(oldPart, newPart);

		// 删除所有关联的文档的Link关系
		PartRelatedDocUtil.removeAllRelatedDocs(newPart);

		// 清空sourcing驳回原因
		Hashtable<String, String> ibamap = new Hashtable<String, String>();
		ibamap = addToHashtable(ibamap, "SourcingRejectReason", "");
		IBAUtil.setSoftTypeIBAValues(newPart, ibamap);

		// 清空Sourcing二级物料BOM信息
		ibamap = addToHashtable(ibamap, "SourcingUpdateReason", "");
		IBAUtil.setSoftTypeIBAValues(newPart, ibamap);

		return newPart;

	}

	/**
	 * 实现Hashtable添加数据时不会出现空指针异常
	 *从ext\tianma\part\PartCommands.java,复制而来;编译问题
	 * @param hashtable
	 * @param key
	 * @param value
	 * @return
	 */
	private static Hashtable<String, String> addToHashtable(Hashtable<String, String> hashtable, String key,
															String value) {
		if (key == null && hashtable != null) {
			return hashtable;
		}

		if (value == null && hashtable != null) {
			return hashtable;
		}

		if (key == null && hashtable == null) {
			return new Hashtable<String, String>();
		}

		if (value == null && hashtable == null) {
			return new Hashtable<String, String>();
		}

		if (hashtable == null) {
			hashtable = new Hashtable<String, String>();
		}
		hashtable.put(key, value);

		return hashtable;
	}
}
